# widgets.py

from django import forms
from django.conf import settings

from django.forms.widgets import flatatt
from django.forms.util import smart_unicode
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse, resolve, NoReverseMatch
from xadmin.ajax.widgets import AjaxInput

        
class BaseAjaxAutoCompleteInput(AjaxInput, forms.Select):
    class Media(AjaxInput.Media):
        js = (
              settings.XADMIN_MEDIA_URL + "js/jquery/jquery-1.3.2.min.js",
              settings.XADMIN_MEDIA_URL + "js/jquery/jquery.autocomplete.pack.js",
              settings.XADMIN_MEDIA_URL + "js/jquery/jquery-ui.1.7.2.min.js",
              )
        css = {
            'all': (settings.XADMIN_MEDIA_URL + "css/jquery.autocomplete.css",)
        }
                      
class AjaxLookupInput(BaseAjaxAutoCompleteInput):
    template = 'xadmin/widgets/ajax_lookup_input.html'
    input_type = 'hidden'
    
    def __init__(self, ajax_service_view, attrs={}):
        self.service_url_name = str(ajax_service_view) 
        self._extrafilters = {}    
        attrs['type'] = 'hidden'
        self.autocomplete_options = {}
        self.autocomplete_options.update( attrs.pop('autocomplete_options', {}) )                
        super(AjaxLookupInput, self).__init__(attrs)
         
    def label_for_value(self, value):
        obj = ""
        if value:
            try:
                service, args, kwargs = resolve( reverse(self.service_url_name) )
                obj = service.queryset.get(pk=value)
            except AttributeError, e:
                raise AttributeError("<Error!! is '%s' an AjaxService instance ?>" % service, e)
#            except service.queryset.model.DoesNotExist:
#                pass
                #raise Exception( value )
            except NoReverseMatch:
                raise NoReverseMatch( "Cannot reverse '%s'" % self.service_url_name )
            except Exception, e:
                raise e
        return str(obj)

    def _get_context(self, name, value=None, attrs=None):
        attrs['label'] =  self.label_for_value(value)        
        p = super(AjaxLookupInput, self)._get_context(name, value, attrs)
        p.update( {'source': reverse (self.service_url_name) ,
                   'options': self.autocomplete_options,
                   })
        return  p



    
            
